package com.bs.blogspace.controller;

import com.bs.blogspace.mapper.UserMapper;
import com.bs.blogspace.model.Result;
import com.bs.blogspace.pojo.User;
import com.bs.blogspace.service.UserService;
import com.bs.blogspace.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /*用户注册*/
    @PostMapping("/register")
    @ResponseBody
    public Result<Object> register(@RequestBody User user) {
        log.info("注册新用户信息：{}", user);
        Result<Object> result = new Result<>();
        Result<User> register = userService.register(user.getUserName(), user.getPassword(), user.getPhone());
        if (register != null){
            HashMap<String, Object> clamis = new HashMap<>();
            clamis.put("username",register.getData().getUserName());
            //log.info("获取ID：{}",register.getData().getId());
            String jwt = JwtUtils.generateJwt(clamis);
            result.setSuccess(true);
            result.setData(jwt);
            result.setCode("200");
            return result;
        }
        result.setMessage("用户名或密码错误");
        return  result;

    }

    /*用户登录信息*/
    @PostMapping("/login")
    @ResponseBody
    public Result<Object> login(@RequestBody User user) {
        log.info("用户登录信息：{}", user);
        Result<User> userLogin = userService.login(user.getPhone(), user.getPassword());
        Result<Object> result = new Result<>();
        if (userLogin != null){
            HashMap<String, Object> clamis = new HashMap<>();
            clamis.put("id",userLogin.getData().getId());
            log.info("获取ID：{}",userLogin.getData().getId());
            String jwt = JwtUtils.generateJwt(clamis);
            result.setSuccess(true);
            result.setData(jwt);
            result.setCode("200");
            //result.setMessage(jwt);
            return result;
        }
        result.setMessage("用户名或密码错误");
        return  result;

    }

    /*更新用户信息*/
    @PostMapping("/updateUserMess")
    @ResponseBody
    public Result<User> update(@RequestBody User user){
        log.info("更新用户信息：{}",user);
        return userService.update(user);
    }

    /*查看指定用户信息*/
    @GetMapping("/getUserMess")
    @ResponseBody
    public Result<User> queryGetByPhone(@Param("phone") String phone){
        log.info("根据手机号，查看用户的所有信息：{}",phone);
        return userService.queryGetByPhone(phone);
    }

}


